package org.gulugulubiao.handler;

import lombok.extern.slf4j.Slf4j;
import net.sourceforge.htmlunit.corejs.javascript.EvaluatorException;

import org.gulugulubiao.exception.BaseException;
import org.gulugulubiao.exception.DeletionNotAllowedException;
import org.gulugulubiao.exception.WrongAnswerWithBadGrammarException;
import org.gulugulubiao.result.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.script.ScriptException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
    public Result exceptionHandler(WrongAnswerWithBadGrammarException ex) {
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 捕获业务异常
     *
     * @param ex 异常
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex) {
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 用户已存在
     *
     * @param ex
     * @return
     */
//    @ExceptionHandler
//    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex) {
//        log.error("SQL异常！"+ex);
//
//        //Duplicate entry 'zhangsan' for key 'employee.idx_username'
//        if (ex.getMessage().contains("Duplicate entry")) {
//            String[] s = ex.getMessage().split(" ");
//            return Result.error("1111111"+s[2] + MessageConstant.ALREADY_EXISTS);
//        } else {
//            return Result.error(MessageConstant.UNKNOWN_ERROR);
//        }
//    }


    @ExceptionHandler
    public void exceptionHandler(ScriptException ex) {
        log.error("爬的时候有点异常");
        //return Result.error(ex.getMessage());
    }

    @ExceptionHandler
    public void exceptionHandler(EvaluatorException ex) {
        log.error("爬的时候有点异常");
        //return Result.error(ex.getMessage());
    }


    /**
     * 删除category的时候，如何category绑定了别的，就不能删除
     *
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(DeletionNotAllowedException ex) {
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }


}
